package com.googlecode.mbhsrobopro.controller.gamepad;

import java.util.HashMap;

import net.java.games.input.Component;
import net.java.games.input.Controller;

public class PS2Controller {

	private static HashMap<Float, Direction> directionMap = new HashMap<Float, Direction>();
	
	private static final int LEFT_Y = 0, LEFT_X = 1, RIGHT_Y = 2, RIGHT_X = 3, D_PAD = 4;
	
	private Controller controller;
	
	public PS2Controller(Controller controller) {
		this.controller = controller;
	}
	
	public static void initDirectionMap() {
		for (Direction d : Direction.values())
			directionMap.put(d.value, d);
	}
	
	private boolean getDigitalState(Component c) {
		if (c.getPollData() != c.getDeadZone())
			return true;
		else
			return false;
	}
	
	public void pollController() {
		controller.poll();
	}
	
	public Component getComponentAt(int index) {
		return controller.getComponents()[index];
	}
	
	public Component[] getComponents() {
		return controller.getComponents();
	}
	
	public StickLocation getLeftStickState() {
		return new StickLocation(getComponentAt(LEFT_Y).getPollData(), getComponentAt(LEFT_X).getPollData());
	}
	
	public boolean isLeftStickNeutral() {
		return getLeftStickState().isAtOrigin();
	}
	
	public StickLocation getRightStickState() {
		return new StickLocation(getComponentAt(RIGHT_Y).getPollData(), getComponentAt(RIGHT_X).getPollData());
	}
	
	public boolean isRightStickNeutral() {
		return getRightStickState().isAtOrigin();
	}

	public boolean getButtonState(Button b) {
		return getDigitalState(controller.getComponents()[b.getIndex()]);
	}
	
	public Direction getDPadDirection() {
		return directionMap.get(getComponentAt(D_PAD).getPollData());
	}

	public enum Button {
		TRIANGLE(0), CIRCLE(1), CROSS(2), SQUARE(3),
		L1(6), L2(4), L3(10), R1(7), R2(5), R3(11),
		START(9), SELECT(8);
		
		private int index;
		
		private Button(int index) {
			this.index = index;
		}
		
		public int getIndex() {
			return index + 5;
		}
	}
	
	public enum Direction {
		NORTH(.25f), SOUTH(.75f), EAST(.5f), WEST(1.0f),
		NORTHEAST(.375f), NORTHWEST(.125f), SOUTHEAST(.625f), SOUTHWEST(.875f),
		NEUTRAL(0f);
		
		public float value;
		
		private Direction(float value) {
			this.value = value;
		}
		
	}

}
